﻿using Microsoft.Xrm.Sdk;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace isky.Plugin
{
    public class CreatePostSalesorderapprovalHistory : IPlugin
    {
        
        public void Execute(IServiceProvider serviceProvider)
        {
            // Obtain the execution context service from the service provider.
            var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            // Obtain the Organization Service factory service from the service provider
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            var service = factory.CreateOrganizationService(context.UserId);
            try
            {
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    Entity inputEntity = context.InputParameters["Target"] as Entity;
                    // Entity preImageEntity = (context.PreEntityImages != null && context.PreEntityImages.Contains("PreImage")) ? context.PreEntityImages["PreImage"] : null;
                    if (context.PrimaryEntityId == Guid.Empty)
                    {
                        return;
                    }

                    if (inputEntity.Contains("new_status") 
                        && inputEntity.GetAttributeDefaultValue<OptionSetValue>("new_status",null)!=null)
                    {
                       EntityReference entityReference= inputEntity.GetAttributeDefaultValue<EntityReference>("new_salesorder", null);
                        if (entityReference != null)
                        {
                            Entity salesorderentity = new Entity();
                            salesorderentity.Id = entityReference.Id;
                            salesorderentity.LogicalName = "salesorder";
                            salesorderentity.Attributes["new_reviewtime"] = DateTime.Now.ToLocalTime();
                            service.Update(salesorderentity);
                        }
                     
                    }

                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
                throw new NotImplementedException();
            }
        }
    }
}
